package com.example.homework.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.homework.R;
import com.example.homework.bean.RecommendData;

import java.util.ArrayList;
import java.util.List;

public class RecommendAdapter extends RecyclerView.Adapter<RecommendAdapter.RecommendViewHolder> {
    private Context context;
    private ArrayList<RecommendData>list;
    private MyItemClickListener myItemClickListener;

    public RecommendAdapter(Context context, ArrayList<RecommendData> list) {
        this.context = context;
        this.list = list;
    }
    public interface MyItemClickListener {
        void onItemClick(View view,int position);
    }

    public void setMyItemClickListener(MyItemClickListener myItemClickListener) {
        this.myItemClickListener = myItemClickListener;
    }

    @Override
    public RecommendViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_recommend,parent,false);
        RecommendViewHolder recommendViewHolder = new RecommendViewHolder(view,myItemClickListener);
        return recommendViewHolder;
    }

    @Override
    public void onBindViewHolder(RecommendViewHolder holder, int position) {

        holder.icon.setImageResource(list.get(position).getIcon());
        holder.name.setText(list.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static final class RecommendViewHolder extends RecyclerView.ViewHolder{
        ImageView icon;
        TextView name;
         private MyItemClickListener mListener;
        public RecommendViewHolder(View itemView,MyItemClickListener myItemClickListener) {
            super(itemView);
            icon = itemView.findViewById(R.id.recommend_icon);
            name = itemView.findViewById(R.id.recommend_name);
            this.mListener = myItemClickListener;
            itemView.setOnClickListener(view ->{
                if (mListener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) { // 确保位置有效
                        mListener.onItemClick(view, position);}
                }
            });
        }
    }
}
